package org.tr.agent;

import org.tr.generator.Generator;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

/**
 * User: Lior Ben Zeev
 * Date: Aug 23, 2011
 */

public class TimeRunnerAgent {
    public static void premain(String agentArgs, Instrumentation inst) {

        System.out.println("start TimeRunnerAgent");

        ClassFileTransformer transformer = new ClassFileTransformer() {

            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
                byte[] bytes = classfileBuffer;

                if ((!className.startsWith("java/") && !className.startsWith("sun/") && !className.startsWith("javax/") &&
                        !className.equals("org/tr/generator/TimeRunnerTimer") && !className.equals("org/tr/generator/TimeRunnerDate") &&
                        !className.equals("org/tr/generator/Generator"))) {
                    //System.out.println("Before replace: "+className);


                    String slashedClassName = className.replaceAll("/",".");

                    try {
                        bytes = Generator.getModifedClass(slashedClassName, bytes);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return bytes;
            }
        };
        System.out.println("before addTransformer");
        inst.addTransformer(transformer, false);
        System.out.println("after addTransformer");
    }
}
